﻿package com.cw.war.ui
{
	import com.cw.loader.AssetsLoader;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;


	/**
	 * @author DanielLu
	 */
	public class LoadIcon
	{
		private var iconMC : MaskedSprite;
		private var iconLoader : AssetsLoader;
		private var adapeSize : Boolean = false;

		public function LoadIcon(mc:DisplayObjectContainer, type:String="a")
		{
			this.iconMC = new MaskedSprite ();
			if(type == "a")
			{
				this.iconMC.x = mc.x;
				this.iconMC.y = mc.y;
			}
			else
			{
				this.iconMC.x = mc.parent.x - 3;
				this.iconMC.y = mc.parent.y + 3;
			}
			
			this.iconMC.setMaskBound ( 0 , 0 , mc.width , mc.height );
			mc.parent.addChildAt ( this.iconMC , mc.parent.getChildIndex ( mc ) );
			mc.parent.removeChild ( mc );

			this.iconLoader = new AssetsLoader ();
			this.iconLoader.addCompleteListener ( this.__onLoadIconCompleted );
			this.iconMC.addChild ( this.iconLoader );
		}

		private function __onLoadIconCompleted ( e : Event ) : void
		{
			if (this.adapeSize)
			{
				this.iconLoader.x = this.iconLoader.y = 0;
				var b : Rectangle = this.iconMC.getMaskBound ();
				this.iconLoader.width = b.width;
				this.iconLoader.height = b.height;
			}
			else
			{
				this.iconLoader.x = (this.iconMC.width - this.iconLoader.width) / 2;
				this.iconLoader.y = (this.iconMC.height - this.iconLoader.height) / 2;
			}
		}

		/**
		 * 设置图标
		 */
		public function loadIcon ( path : String ) : void
		{
			if (path == "" || path == null)
			{
				this.iconLoader.close ();
				this.iconLoader.unload ();
				return;
			}
			if (this.iconLoader.getPath () != path)
			{
				this.iconLoader.close ();
				this.iconLoader.unload ();
				this.iconLoader.setPath ( path );
				this.iconLoader.doLoad ();
			}
		}

		public function unloadIcon () : void
		{
			this.iconLoader.close ();
			this.iconLoader.unload ();
		}

		public function getDisplayObject () : DisplayObject
		{
			return this.iconLoader;
		}

		public function getContainer () : Sprite
		{
			return this.iconMC;
		}

		public function setAdaptSize ( adapeSize : Boolean ) : void
		{
			this.adapeSize = adapeSize;
		}

		public function isAdaptSize () : Boolean
		{
			return this.adapeSize;
		}
	}
}
